import 'package:bilibili_getx/core/constant_util/app_theme.dart';
import 'package:bilibili_getx/core/debug/debug_util.dart';
import 'package:bilibili_getx/ui/widgets/custom/highlight_str_in_text.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';

import '../../../../../core/service/request/search_request.dart';
import 'search_state.dart';

class SearchLogic extends GetxController with HYAppTheme {
  final SearchState state = SearchState();

  @override
  void onReady() {
    ///初始化监听输入框输入
    initFocusNode();

    ///获取搜索热词
    initSearchKeywords();

    ///获取推荐搜索词(防抖)
    debounce<String>(state.isInputKeyword, (inputText) async {
      DU.l(inputText);
      if (inputText.isEmpty) {
        return;
      }
      final value =
          await HYSearchRequest().getSearchKeywordRecommendData(inputText);
      if (value.result == null) {
        return;
      }
      SmartDialog.show(
        useAnimation: false,
        maskWidget: Container(),
        builder: (ctx) {
          return Container(
            height: 1.sh - 80.r,
            width: 1.sw,
            color: norTextColors.withOpacity(.3),
            alignment: Alignment.topCenter,
            child: Container(
              height: 0.5.sh,
              color: norWhite01Color,
              child: ListView.separated(
                shrinkWrap: true,
                itemBuilder: (ctx, index) {
                  String searchItemText = value.result!.tag[index].name;
                  return GestureDetector(
                    onTap: () {
                      finishInputAndStartSearch(searchItemText);
                    },
                    child: Container(
                      padding: EdgeInsets.only(bottom: 5.r, left: 20.r),
                      child: HYHighlightStrInText(
                        originalColor: norTextColors,
                        highlightColor: norMainThemeColors,
                        highlightText: inputText,
                        originalText: value.result!.tag[index].name,
                      ),
                    ),
                  );
                },
                separatorBuilder: (ctx, index) {
                  return Container(
                    padding: EdgeInsets.symmetric(horizontal: 20.r),
                    child: const Divider(),
                  );
                },
                itemCount: value.result!.tag.length,
              ),
            ),
          );
        },
        alignment: Alignment.bottomCenter,
      );
      SmartDialog.dismiss();
    });
    super.onReady();
  }

  @override
  void onClose() {
    state.textEditingController.removeListener(() {});
    state.textEditingController.dispose();
    state.focusNode.dispose();
  }

  void initFocusNode() {
    state.focusNode.addListener(() {
      if (state.focusNode.hasFocus) {
        // print('得到焦点');
      } else {
        // print('失去焦点');
      }
    });
  }

  void initSearchKeywords() {
    HYSearchRequest().getSearchKeywordData().then((value) {
      state.searchKeyword = value;
      state.trendingList = state.searchKeyword.data[0].data!.list!;
      update();
    });
  }

  ///完成输入并开始搜索，获取所有结果
  void finishInputAndStartSearch(String text) {
    state.searchKeywordText = text;

    ///关闭弹框
    SmartDialog.dismiss();

    ///设置文本
    state.textEditingController.text = text;

    ///失去焦点
    unFocusFunction();

    ///隐藏键盘
    hideKeyBoard();

    ///获取搜索的结果
    HYSearchRequest().getSearchResultData(text).then((searchResultData) {
      ///显示搜索结果
      state.showResult = true;
      state.searchResult = searchResultData;
      update();
    });
  }

  void clearSearchKey(BuildContext context) {
    state.textEditingController.clear();

    ///获取焦点
    FocusScope.of(context).requestFocus(state.focusNode);
  }

  ///失去焦点
  void unFocusFunction() {
    state.focusNode.unfocus();
  }

  ///隐藏键盘而不丢失文本字段焦点：
  void hideKeyBoard() {
    SystemChannels.textInput.invokeMethod('TextInput.hide');
  }

  /// 推荐关键字
  Future<void> getRecommendSearchKey(String inputText) async {
    state.isInputKeyword.value = inputText;
  }
}
